<?php

namespace Aoe\Attributes\Controller;


use Aoe\Core\Controller;
use Aoe\Intent\Request\Http;
use Aoe\Intent\Request\Request;
use Attribute;
use Closure;

/**
 * # 超级管理员校验中间件
 */
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_CLASS)]
class Super extends CtrlAttribute
{
    const string ERR_SUPER  = '需要超级管理员权限';
    
    public function __construct(private readonly bool $super = true) {}

    protected function core(Request $request, Controller $controller, ?Closure $next): void
    {
        if ($this->check($request)) $next && $next($request);
    }

    /**
     * ## 内部-权限认证
     *
     * @param Request $request
     * @return bool
     */
    private function check(Request $request): bool
    {
        // 内部执行不检查权限
        if (!$request instanceof Http) return true;
        
        $user = $request->user;
        if (!$user->logged) {
            $this->_to_login($request);
            return false;
        }
        
        if (!$this->super) return true;
        
        if (!$user->isAdministrator()) {
            $request->response->error(self::ERR_SUPER);
            return false;
        }
        
        // 超级管理员
        return true;
    }
    
    private function _to_login(Http $request): void
    {
        $request->pushCurrentUri();
        $request->response->complete(
            ['redirect' => $request->compileUrl(LOGIN_CMD)],
            true
        );
    }
}